#!/bin/sh
# Author: Narunas Krasauskas
# Purpose: Helper script for package kvm-init
# Tested On: Debian GNU/Linux 6.0.7 (squeeze) x86_64
# Version: 1a
# Time: 2013/11/24
# Copyright: GPLv3
# Use with caution! Author doesn't take any responsibility for any damage
# caused using these scripts.

## Variables
_if0=eth0
_if1=$1
_br0=kvm-br0

## Tools
_IP="/sbin/ip"
_DHCLIENT="/sbin/dhclient"
_IFCONFIG="/sbin/ifconfig"
_TUNCTL="/usr/sbin/tunctl"

echo "Executing /etc/qemu-ifdown:"


## Counting tun/tap interfaces
## There should be as many as VM instances
_n=$($_IP link show | grep -Eo 'tap[0-9]{1,2}' | wc -w)

## Getting rid of no longer used tun/tap interface
$_TUNCTL -d $_if1 && sleep 1
$_IP link delete dev $_if1 &> /dev/null

## If the last VM shut down, then bridge is also no longer needed
## Therefore let's burn it
if [ "$_n" -lt 2 ]; then
	$_DHCLIENT -r $_br0
	$_IP link delete dev $_br0 && sleep 1
	# Reconfigure primary interface to function as normal
	$_IP link set dev $_if0 down && sleep 1
	$_IFCONFIG $_if0 0.0.0.0 -promisc up && $_DHCLIENT $_if0
fi
